import router, { constantRoutes, dynamicRoutes } from "@/router";
import { isHttp } from "@/utils/validate";
import { getRouters } from "@/api/menu";
import Layout from "@/layout/index";
import ParentView from "@/components/ParentView";
import InnerLink from "@/layout/components/InnerLink";
import useUserStore from '@/store/modules/user';
// 匹配views里面所有的.vue文件
const modules = import.meta.glob("./../../views/**/*.vue");


const usePermissionStore = defineStore('permission', {
	state: () => ({
		routes: [],
		addRoutes: [],
		defaultRoutes: [],
		topbarRouters: [],
		sidebarRouters: []
	}),
	// getters: {},
	actions: {
		setRoutes(routes) {
			this.addRoutes = routes
			this.routes = constantRoutes.concat(routes)
		},
		setDefaultRoutes(routes) {
			this.defaultRoutes = constantRoutes.concat(routes)
		},
		setTopbarRoutes(routes) {
			this.topbarRouters = routes
		},
		setSidebarRouters(routes) {
			this.sidebarRouters = routes
		},
		generateRoutes(userId) {
			return new Promise(resolve => {
				// 向后端请求路由数据
				getRouters(userId).then(res => {
					const { phone } = useUserStore();
					// 开发环境, 测试用户显示开发用例
					if(import.meta.env.VITE_APP_ENV === "development" && phone == "15201572964"){
						// 加上数学公式路由界面
						if(res.data && res.data.length){
							res.data.unshift({
								path: "/tool",
								name: "tool",
								meta: { icon: 'fa fa-fw fa-navicon', title: '开发用例' },
								component: 'Layout',
								redirect: "/tool/math",
								alwaysShow: true,
								// 数学公式
								children: [{
									path: "math",
									name: "math",
									meta: { icon: 'fa fa-fw fa-navicon', title: '数学公式' },
									component: 'tool/math/index', // 开始不要/
									alwaysShow: false,
									children: null
								}]
							});
						}
					}
					const sdata = JSON.parse(JSON.stringify(res.data))
					const rdata = JSON.parse(JSON.stringify(res.data))
					const defaultData = JSON.parse(JSON.stringify(res.data))
					const sidebarRoutes = filterAsyncRouter(sdata)
					const rewriteRoutes = filterAsyncRouter(rdata, false, true)
					const defaultRoutes = filterAsyncRouter(defaultData)
					this.setRoutes(rewriteRoutes)
					this.setSidebarRouters(constantRoutes.concat(processDynamicRoutes(sidebarRoutes)))
					this.setDefaultRoutes(processDynamicRoutes(sidebarRoutes))
					this.setTopbarRoutes(defaultRoutes)
					// 动态添加路由到路由表中
					// addRoutes(rewriteRoutes.concat(processDynamicRoutes(dynamicRoutes)));
					addRoutes(rewriteRoutes.concat(dynamicRoutes));
					resolve(rewriteRoutes)
				})
			})
		}
	}
})

function processDynamicRoutes(routes) {
	// 处理重大工程中的菜单隐藏
	const hiddenList = ['pipelineVulnerManagement','nuclearPowerVulnerManagement','reservoirDamVulnerManagement','otherMajorVulnerManagement']
    routes.forEach(route => {
        if (route.children && route.children.length) {
            route.children.forEach(child => {
                if (hiddenList.includes(child.path)) {
                    child.hidden = true;
                }
            });
        }
    });
	return routes
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
	return asyncRouterMap.filter((route) => {
		if (type && route.children) {
			route.children = filterChildren(route.children);
		}
		if (route.component) {
			// Layout ParentView 组件特殊处理
			if (route.component === "Layout") {
				route.component = Layout;
			} else if (route.component === "ParentView") {
				route.component = ParentView;
			} else if (route.component === "InnerLink") {
				route.component = InnerLink;
			} else {
				route.component = loadView(route.component);
			}
		}
		if (route.children != null && route.children && route.children.length) {
			route.children = filterAsyncRouter(route.children, route, type);
		} else {
			delete route["children"];
			delete route["redirect"];
		}
		return true;
	});
}

function filterChildren(childrenMap, lastRouter = false) {
	var children = [];
	childrenMap.forEach((el, index) => {
		if (el.children && el.children.length) {
			if (el.component === "ParentView" && !lastRouter) {
				el.children.forEach((c) => {
					c.path = el.path + "/" + c.path;
					if (c.children && c.children.length) {
						children = children.concat(filterChildren(c.children, c));
						return;
					}
					children.push(c);
				});
				return;
			}
		}
		if (lastRouter) {
			el.path = lastRouter.path + "/" + el.path;
		}
		children = children.concat(el);
	});
	return children;
}

// 动态添加路由到路由表中
function addRoutes(routes) {
	if(routes && routes.length) {
	  // 根据roles权限生成可访问的路由表
	  routes.forEach((route) => {
			if (!isHttp(route.path)) {
				const arrRoutes = router.getRoutes().map(item => item.name);
				if(arrRoutes.includes(route.name) && route.children && route.children.length){
					route.children.map(cur => {
						router.addRoute(route.name, cur);
					})
				} else {
					router.addRoute(route); // 动态添加可访问路由表
				}
			}
	  });
	}
}

export const loadView = (view) => {
	let res;
	for (const path in modules) {
		const dir = path.split("views/")[1].split(".vue")[0];
		if (dir === view) {
			res = () => modules[path]();
		}
	}
	return res;
};

export default usePermissionStore;
